from django.shortcuts import render

# Create your views here.
from rest_framework.generics import ListAPIView
from .models import CourseCategory
from .serializers import CourseCategoryModelSerializer
"""模型->视图->序列化器->路由"""
class CourseCategoryListAPIView(ListAPIView):
    """课程分类列表"""
    queryset = CourseCategory.objects.filter(is_show=True,is_delete=False).order_by("orders", "-id")
    serializer_class = CourseCategoryModelSerializer

from .models import Course
from .serializers import CourseModelSerializer
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from .paginations import CourseListPagination

class CourseListAPIView(ListAPIView):
    """课程列表"""
    queryset = Course.objects.filter(is_show=True,is_delete=False).order_by("orders", "-id")
    serializer_class = CourseModelSerializer
    filter_backends = [DjangoFilterBackend,OrderingFilter]
    filter_fields = ["course_category"]
    ordering_fields = ["id","students","price"]
    pagination_class = CourseListPagination


from rest_framework.generics import RetrieveAPIView
from .models import Course
from .serializers import CourseRetrieveModelSerializer
class CourseRetrieveAPIView(RetrieveAPIView):
    """课程详情接口"""
    queryset = Course.objects.filter(is_show=True,is_delete=False)
    serializer_class = CourseRetrieveModelSerializer

from .models import CourseChapter
from .serializers import CourseChapterModelSerializer
class ChapterListAPIView(ListAPIView):
    """课程章节列表"""
    queryset = CourseChapter.objects.filter(is_show=True, is_delete=False).order_by("chapter")
    serializer_class = CourseChapterModelSerializer
    filter_backends = [DjangoFilterBackend]
    filter_fields = ["course"]

from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from users.models import UserCourse
from courses.models import CourseLesson
from rest_framework.response import Response
from rest_framework import status
from datetime import datetime
from django.conf import settings
from luffyapi.libs.polyv import PolyvPlayer

class PolyvAPIView(APIView):
    permission_classes = [IsAuthenticated]
    """保利威加密视频接口"""
    def get(self,request,course_id, lesson_id):
        """获取授权码token"""
        user = request.user
        try:
            lesson = CourseLesson.objects.get(id=lesson_id)
        except:
            return Response({"message": "当前课时视频不存在！", }, status=status.HTTP_400_BAD_REQUEST)

        if not lesson.free_trail:
            # 判断用户是否购买了视频
            try:
                user_course = UserCourse.objects.get(user_id=user.id, course_id=course_id)
                # todo 判断购买是否过期
                out_timestamp = user_course.out_time.timestamp()
                now_timestamp = datetime.now().timestamp()
                if now_timestamp > out_timestamp:
                    # 购买过期了
                    raise
            except:
                return Response({"message":"您没有购买当前视频或者视频购买已过期！"}, status=status.HTTP_400_BAD_REQUEST)

        # 生成token
        userId = settings.POLYV_CONFIG["userId"]
        secretkey = settings.POLYV_CONFIG["secretkey"]
        tokenUrl = settings.POLYV_CONFIG["tokenUrl"]

        user_ip = request.META.get("REMOTE_ADDR")  # 用户的IP

        try:
            polyv = PolyvPlayer(userId,secretkey,tokenUrl)
            result = polyv.get_video_token(lesson.lesson_link, user_ip, user.id, user.username)
            return Response(result.get("token"))
        except:
            return Response({"message":"获取视频播放授权失败！"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)